/**
 * Worker Manager
 * 
 * High-level API for managing worker pools
 */

import { WorkerPool } from './worker-pool';
import { logger } from '@/utils/logger';
import type { AgentOptions } from '@/types';
import path from 'path';

/**
 * Worker Manager
 * 
 * Manages worker pools for different task types
 */
export class WorkerManager {
  private agentPool: WorkerPool | null = null;
  private initialized = false;

  /**
   * Initialize worker pools
   */
  async initialize(): Promise<void> {
    if (this.initialized) {
      return;
    }

    logger.info('Initializing worker manager');

    // Create agent worker pool
    const workerScript = path.join(__dirname, 'agent-worker.ts');

    this.agentPool = new WorkerPool({
      minWorkers: 2,
      maxWorkers: 4,
      workerScript,
      workerOptions: {
        smol: false, // Use normal memory mode for better performance
        ref: false,  // Don't keep process alive
      },
      taskTimeout: 60000, // 60 seconds
    });

    this.initialized = true;

    logger.info('Worker manager initialized');
  }

  /**
   * Execute agent query in parallel
   */
  async executeAgentQuery(
    prompt: string,
    options?: AgentOptions
  ): Promise<string> {
    if (!this.initialized || !this.agentPool) {
      throw new Error('Worker manager not initialized');
    }

    return this.agentPool.submit('agent_query', { prompt, options });
  }

  /**
   * Execute multiple agent queries in parallel
   */
  async executeAgentQueriesParallel(
    queries: Array<{ prompt: string; options?: AgentOptions }>
  ): Promise<string[]> {
    if (!this.initialized || !this.agentPool) {
      throw new Error('Worker manager not initialized');
    }

    logger.info('Executing parallel queries', { count: queries.length });

    const promises = queries.map(({ prompt, options }) =>
      this.agentPool!.submit('agent_query', { prompt, options })
    );

    const results = await Promise.all(promises);

    logger.info('Parallel queries completed', { count: results.length });

    return results;
  }

  /**
   * Execute tool in worker
   */
  async executeTool(toolName: string, args: any): Promise<any> {
    if (!this.initialized || !this.agentPool) {
      throw new Error('Worker manager not initialized');
    }

    return this.agentPool.submit('tool_execution', { toolName, args });
  }

  /**
   * Get statistics
   */
  getStatistics() {
    if (!this.initialized || !this.agentPool) {
      return {
        initialized: false,
        agentPool: null,
      };
    }

    return {
      initialized: true,
      agentPool: this.agentPool.getStatistics(),
    };
  }

  /**
   * Shutdown worker manager
   */
  async shutdown(): Promise<void> {
    if (!this.initialized) {
      return;
    }

    logger.info('Shutting down worker manager');

    if (this.agentPool) {
      await this.agentPool.shutdown();
      this.agentPool = null;
    }

    this.initialized = false;

    logger.info('Worker manager shut down');
  }
}

/**
 * Global worker manager instance
 */
export const workerManager = new WorkerManager();

